// JSON数据存储服务
import type { Case } from '../models/Case';
import type { Suspect } from '../models/Suspect';
import type { Evidence } from '../models/Evidence';
import type { Interrogation } from '../models/Interrogation';
import type { PlayerStatistics, CaseRecord } from '../models/Statistics';

// 导入默认数据
import defaultCases from '../data/defaultCases.json';
import defaultSuspects from '../data/defaultSuspects.json';
import defaultAchievements from '../data/defaultAchievements.json';

// 数据存储结构
interface AppData {
  cases: Case[];
  suspects: Suspect[];
  evidences: Evidence[];
  interrogations: Interrogation[];
  statistics: PlayerStatistics;
}

// 生成唯一ID的工具函数
function generateId(): string {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

// JSON存储服务类
export class JsonStorageService {
  private data: AppData | null = null;
  private readonly STORAGE_KEY = 'ai_detective_app_data';

  constructor() {
    this.loadData();
  }

  // 从本地存储加载数据
  private loadData(): void {
    try {
      const storedData = localStorage.getItem(this.STORAGE_KEY);
      if (storedData) {
        this.data = JSON.parse(storedData);
        // 转换日期字符串为Date对象
        this.convertDates();
      } else {
        // 初始化默认数据
        this.initializeDefaultData();
      }
    } catch (error) {
      console.error('加载数据失败:', error);
      this.initializeDefaultData();
    }
  }

  // 保存数据到本地存储
  private saveData(): void {
    try {
      if (this.data) {
        localStorage.setItem(this.STORAGE_KEY, JSON.stringify(this.data));
      }
    } catch (error) {
      console.error('保存数据失败:', error);
    }
  }

  // 转换日期字符串为Date对象
  private convertDates(): void {
    if (!this.data) return;

    // 转换案件日期
    this.data.cases.forEach(caseItem => {
      caseItem.createdTime = new Date(caseItem.createdTime);
    });

    // 转换证据日期
    this.data.evidences.forEach(evidence => {
      evidence.discoveryTime = new Date(evidence.discoveryTime);
      if (evidence.analysis.lastAnalyzedTime) {
        evidence.analysis.lastAnalyzedTime = new Date(evidence.analysis.lastAnalyzedTime);
      }
    });

    // 转换审讯日期
    this.data.interrogations.forEach(interrogation => {
      interrogation.startTime = new Date(interrogation.startTime);
      if (interrogation.endTime) {
        interrogation.endTime = new Date(interrogation.endTime);
      }
      interrogation.dialogues.forEach(dialogue => {
        dialogue.timestamp = new Date(dialogue.timestamp);
      });
      interrogation.keyPoints.forEach(keyPoint => {
        keyPoint.timestamp = new Date(keyPoint.timestamp);
      });
    });

    // 转换统计数据日期
    if (this.data.statistics) {
      this.data.statistics.lastUpdated = new Date(this.data.statistics.lastUpdated);
      this.data.statistics.caseRecords.forEach(record => {
        record.startTime = new Date(record.startTime);
        if (record.endTime) {
          record.endTime = new Date(record.endTime);
        }
      });
      this.data.statistics.achievements.forEach(achievement => {
        if (achievement.unlockedTime) {
          achievement.unlockedTime = new Date(achievement.unlockedTime);
        }
      });
    }
  }

  // 初始化默认数据
  private initializeDefaultData(): void {
    // 转换案件数据，将字符串日期转换为Date对象
    const casesWithDate = defaultCases.map((c: any) => ({
      ...c,
      createdTime: new Date(c.createdTime)
    }));
    
    // 转换成就数据，将字符串类别转换为枚举值
    const achievementsWithEnum = defaultAchievements.map((a: any) => ({
      ...a,
      category: a.category as any
    }));
    
    this.data = {
      cases: casesWithDate,
      suspects: defaultSuspects,
      evidences: [],
      interrogations: [],
      statistics: {
        totalCases: 2,
        completedCases: 0,
        successfulCases: 0,
        failureCases: 0,
        successRate: 0,
        totalPlayTime: 0,
        averageSolveTime: 0,
        caseRecords: [],
        achievements: achievementsWithEnum,
        lastUpdated: new Date()
      }
    };
    this.saveData();
  }

  // 案件相关方法
  async getCases(): Promise<Case[]> {
    return this.data?.cases || [];
  }

  async getCaseById(id: string): Promise<Case | undefined> {
    return this.data?.cases.find(c => c.id === id);
  }

  async updateCase(updatedCase: Case): Promise<void> {
    if (!this.data) return;
    const index = this.data.cases.findIndex(c => c.id === updatedCase.id);
    if (index !== -1) {
      this.data.cases[index] = updatedCase;
      this.saveData();
    }
  }

  // 嫌疑人相关方法
  async getSuspects(): Promise<Suspect[]> {
    return this.data?.suspects || [];
  }

  async getSuspectById(id: string): Promise<Suspect | undefined> {
    return this.data?.suspects.find(s => s.id === id);
  }

  async getSuspectsByCaseId(caseId: string): Promise<Suspect[]> {
    const caseItem = await this.getCaseById(caseId);
    if (!caseItem || !this.data) return [];
    return this.data.suspects.filter(s => caseItem.suspects.includes(s.id));
  }

  // 证据相关方法
  async getEvidences(): Promise<Evidence[]> {
    return this.data?.evidences || [];
  }

  async getEvidencesByCaseId(caseId: string): Promise<Evidence[]> {
    return this.data?.evidences.filter(e => e.caseId === caseId) || [];
  }

  async addEvidence(evidence: Omit<Evidence, 'id'>): Promise<Evidence> {
    if (!this.data) throw new Error('数据未初始化');
    const newEvidence: Evidence = {
      ...evidence,
      id: generateId()
    };
    this.data.evidences.push(newEvidence);
    this.saveData();
    return newEvidence;
  }

  async updateEvidence(updatedEvidence: Evidence): Promise<void> {
    if (!this.data) return;
    const index = this.data.evidences.findIndex(e => e.id === updatedEvidence.id);
    if (index !== -1) {
      this.data.evidences[index] = updatedEvidence;
      this.saveData();
    }
  }

  // 审讯相关方法
  async getInterrogations(): Promise<Interrogation[]> {
    return this.data?.interrogations || [];
  }

  async getInterrogationsByCaseId(caseId: string): Promise<Interrogation[]> {
    return this.data?.interrogations.filter(i => i.caseId === caseId) || [];
  }

  async addInterrogation(interrogation: Omit<Interrogation, 'id'>): Promise<Interrogation> {
    if (!this.data) throw new Error('数据未初始化');
    const newInterrogation: Interrogation = {
      ...interrogation,
      id: generateId()
    };
    this.data.interrogations.push(newInterrogation);
    this.saveData();
    return newInterrogation;
  }

  async updateInterrogation(updatedInterrogation: Interrogation): Promise<void> {
    if (!this.data) return;
    const index = this.data.interrogations.findIndex(i => i.id === updatedInterrogation.id);
    if (index !== -1) {
      this.data.interrogations[index] = updatedInterrogation;
      this.saveData();
    }
  }

  // 统计相关方法
  async getStatistics(): Promise<PlayerStatistics> {
    if (!this.data) {
      throw new Error('数据未初始化');
    }
    return this.data.statistics;
  }

  async updateStatistics(updatedStatistics: PlayerStatistics): Promise<void> {
    if (!this.data) return;
    this.data.statistics = updatedStatistics;
    this.data.statistics.lastUpdated = new Date();
    this.saveData();
  }

  async addCaseRecord(record: CaseRecord): Promise<void> {
    if (!this.data) return;
    this.data.statistics.caseRecords.push(record);
    // 更新统计数据
    this.updateStatisticsSummary();
    this.saveData();
  }

  // 更新统计摘要
  private updateStatisticsSummary(): void {
    if (!this.data) return;
    
    const stats = this.data.statistics;
    const records = stats.caseRecords;
    
    stats.completedCases = records.filter(r => r.endTime).length;
    stats.successfulCases = records.filter(r => r.isSuccessful).length;
    stats.failureCases = stats.completedCases - stats.successfulCases;
    stats.successRate = stats.completedCases > 0 ? 
      Math.round((stats.successfulCases / stats.completedCases) * 100) : 0;
    
    // 计算平均破案时间
    const solvedRecords = records.filter(r => r.solveTime);
    if (solvedRecords.length > 0) {
      const totalSolveTime = solvedRecords.reduce((sum, r) => sum + (r.solveTime || 0), 0);
      stats.averageSolveTime = Math.round(totalSolveTime / solvedRecords.length);
    }
    
    // 检查并更新成就进度
    this.updateAchievementsProgress();
  }

  // 更新成就进度
  private updateAchievementsProgress(): void {
    if (!this.data) return;
    
    const stats = this.data.statistics;
    const records = stats.caseRecords;
    
    stats.achievements.forEach(achievement => {
      switch (achievement.id) {
        case 'first_case_solved':
          achievement.progress = stats.successfulCases >= 1 ? 1 : 0;
          if (achievement.progress >= achievement.targetValue && !achievement.isUnlocked) {
            achievement.isUnlocked = true;
            achievement.unlockedTime = new Date();
          }
          break;
        case 'five_cases_solved':
          achievement.progress = stats.successfulCases;
          if (achievement.progress >= achievement.targetValue && !achievement.isUnlocked) {
            achievement.isUnlocked = true;
            achievement.unlockedTime = new Date();
          }
          break;
        case 'perfect_detective':
          achievement.progress = stats.successRate === 100 ? 1 : 0;
          if (achievement.progress >= achievement.targetValue && !achievement.isUnlocked) {
            achievement.isUnlocked = true;
            achievement.unlockedTime = new Date();
          }
          break;
        // 可以添加更多成就的检查逻辑
      }
    });
  }

  // 重置所有数据
  async resetAllData(): Promise<void> {
    localStorage.removeItem(this.STORAGE_KEY);
    this.initializeDefaultData();
  }
}

// 导出单例实例
export const jsonStorageService = new JsonStorageService();